#!/usr/bin/env python3
"""
用户API接口模块
提供用户相关的API调用功能
"""

import json
from typing import Dict, List, Optional, Any
from common.api_client import APIClient
from common.logger import get_logger
from flask import Blueprint

# 创建蓝图
user_bp = Blueprint('user', __name__, url_prefix='/api/users')


class UserAPI:
    """用户API接口类"""
    
    def __init__(self, base_url: str, api_client: Optional[APIClient] = None):
        """
        初始化用户API
        
        Args:
            base_url: API基础URL
            api_client: API客户端实例，如果为None则创建新实例
        """
        self.base_url = base_url.rstrip('/')
        self.api_client = api_client or APIClient(base_url=self.base_url)
        self.logger = get_logger(__name__)
        
        # API端点
        self.endpoints = {
            'users': '/api/users',
            'user_detail': '/api/users/{user_id}',
            'register': '/api/auth/register',
            'login': '/api/auth/login',
            'logout': '/api/auth/logout',
            'profile': '/api/users/profile',
            'change_password': '/api/users/change-password'
        }
    
    def register_user(self, user_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        注册新用户
        
        Args:
            user_data: 用户注册数据
                {
                    "username": "用户名",
                    "email": "邮箱",
                    "password": "密码",
                    "first_name": "名字",
                    "last_name": "姓氏"
                }
        
        Returns:
            注册结果
        """
        self.logger.info(f"注册用户: {user_data.get('username')}")
        
        try:
            response = self.api_client.post(
                self.endpoints['register'],
                data=user_data
            )
            
            if response.get('success'):
                self.logger.info(f"用户注册成功: {user_data.get('username')}")
            else:
                self.logger.warning(f"用户注册失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"用户注册异常: {str(e)}")
            return {
                'success': False,
                'message': f"注册失败: {str(e)}",
                'error': str(e)
            }
    
    def login_user(self, credentials: Dict[str, str]) -> Dict[str, Any]:
        """
        用户登录
        
        Args:
            credentials: 登录凭证
                {
                    "username": "用户名或邮箱",
                    "password": "密码"
                }
        
        Returns:
            登录结果，包含token等信息
        """
        self.logger.info(f"用户登录: {credentials.get('username')}")
        
        try:
            response = self.api_client.post(
                self.endpoints['login'],
                data=credentials
            )
            
            if response.get('success'):
                self.logger.info(f"用户登录成功: {credentials.get('username')}")
                # 设置认证token
                token = response.get('data', {}).get('token')
                if token:
                    self.api_client.set_auth_token(token)
            else:
                self.logger.warning(f"用户登录失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"用户登录异常: {str(e)}")
            return {
                'success': False,
                'message': f"登录失败: {str(e)}",
                'error': str(e)
            }
    
    def logout_user(self) -> Dict[str, Any]:
        """
        用户登出
        
        Returns:
            登出结果
        """
        self.logger.info("用户登出")
        
        try:
            response = self.api_client.post(self.endpoints['logout'])
            
            # 清除认证token
            self.api_client.clear_auth_token()
            
            if response.get('success'):
                self.logger.info("用户登出成功")
            else:
                self.logger.warning(f"用户登出失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"用户登出异常: {str(e)}")
            return {
                'success': False,
                'message': f"登出失败: {str(e)}",
                'error': str(e)
            }
    
    def get_user_profile(self) -> Dict[str, Any]:
        """
        获取当前用户资料
        
        Returns:
            用户资料信息
        """
        self.logger.info("获取用户资料")
        
        try:
            response = self.api_client.get(self.endpoints['profile'])
            
            if response.get('success'):
                self.logger.info("用户资料获取成功")
            else:
                self.logger.warning(f"用户资料获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取用户资料异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取资料失败: {str(e)}",
                'error': str(e)
            }
    
    def update_user_profile(self, profile_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        更新用户资料
        
        Args:
            profile_data: 更新的资料数据
        
        Returns:
            更新结果
        """
        self.logger.info(f"更新用户资料: {profile_data}")
        
        try:
            response = self.api_client.put(
                self.endpoints['profile'],
                data=profile_data
            )
            
            if response.get('success'):
                self.logger.info("用户资料更新成功")
            else:
                self.logger.warning(f"用户资料更新失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"更新用户资料异常: {str(e)}")
            return {
                'success': False,
                'message': f"更新资料失败: {str(e)}",
                'error': str(e)
            }
    
    def change_password(self, password_data: Dict[str, str]) -> Dict[str, Any]:
        """
        修改密码
        
        Args:
            password_data: 密码修改数据
                {
                    "current_password": "当前密码",
                    "new_password": "新密码"
                }
        
        Returns:
            修改结果
        """
        self.logger.info("修改用户密码")
        
        try:
            response = self.api_client.post(
                self.endpoints['change_password'],
                data=password_data
            )
            
            if response.get('success'):
                self.logger.info("密码修改成功")
            else:
                self.logger.warning(f"密码修改失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"修改密码异常: {str(e)}")
            return {
                'success': False,
                'message': f"修改密码失败: {str(e)}",
                'error': str(e)
            }
    
    def get_user_list(self, page: int = 1, limit: int = 10, filters: Optional[Dict] = None) -> Dict[str, Any]:
        """
        获取用户列表
        
        Args:
            page: 页码
            limit: 每页数量
            filters: 过滤条件
        
        Returns:
            用户列表数据
        """
        self.logger.info(f"获取用户列表 - 页码: {page}, 数量: {limit}")
        
        params = {
            'page': page,
            'limit': limit
        }
        
        if filters:
            params.update(filters)
        
        try:
            response = self.api_client.get(
                self.endpoints['users'],
                params=params
            )
            
            if response.get('success'):
                self.logger.info(f"用户列表获取成功，共 {response.get('data', {}).get('total', 0)} 条记录")
            else:
                self.logger.warning(f"用户列表获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取用户列表异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取列表失败: {str(e)}",
                'error': str(e)
            }
    
    def get_user_detail(self, user_id: int) -> Dict[str, Any]:
        """
        获取用户详情
        
        Args:
            user_id: 用户ID
        
        Returns:
            用户详情数据
        """
        self.logger.info(f"获取用户详情: {user_id}")
        
        try:
            endpoint = self.endpoints['user_detail'].format(user_id=user_id)
            response = self.api_client.get(endpoint)
            
            if response.get('success'):
                self.logger.info(f"用户详情获取成功: {user_id}")
            else:
                self.logger.warning(f"用户详情获取失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"获取用户详情异常: {str(e)}")
            return {
                'success': False,
                'message': f"获取详情失败: {str(e)}",
                'error': str(e)
            }
    
    def update_user(self, user_id: int, user_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        更新用户信息
        
        Args:
            user_id: 用户ID
            user_data: 用户数据
        
        Returns:
            更新结果
        """
        self.logger.info(f"更新用户信息: {user_id}")
        
        try:
            endpoint = self.endpoints['user_detail'].format(user_id=user_id)
            response = self.api_client.put(endpoint, data=user_data)
            
            if response.get('success'):
                self.logger.info(f"用户信息更新成功: {user_id}")
            else:
                self.logger.warning(f"用户信息更新失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"更新用户信息异常: {str(e)}")
            return {
                'success': False,
                'message': f"更新失败: {str(e)}",
                'error': str(e)
            }
    
    def delete_user(self, user_id: int) -> Dict[str, Any]:
        """
        删除用户
        
        Args:
            user_id: 用户ID
        
        Returns:
            删除结果
        """
        self.logger.info(f"删除用户: {user_id}")
        
        try:
            endpoint = self.endpoints['user_detail'].format(user_id=user_id)
            response = self.api_client.delete(endpoint)
            
            if response.get('success'):
                self.logger.info(f"用户删除成功: {user_id}")
            else:
                self.logger.warning(f"用户删除失败: {response.get('message')}")
            
            return response
            
        except Exception as e:
            self.logger.error(f"删除用户异常: {str(e)}")
            return {
                'success': False,
                'message': f"删除失败: {str(e)}",
                'error': str(e)
            }


# 使用示例
if __name__ == "__main__":
    # 创建用户API实例
    user_api = UserAPI("http://localhost:8000")
    
    # 测试注册
    test_user = {
        "username": "test_user",
        "email": "test@example.com",
        "password": "password123",
        "first_name": "Test",
        "last_name": "User"
    }
    
    result = user_api.register_user(test_user)
    print("注册结果:", result)
    
    # 测试登录
    credentials = {
        "username": "test_user",
        "password": "password123"
    }
    
    result = user_api.login_user(credentials)
    print("登录结果:", result)
    
    # 测试获取资料
    if result.get('success'):
        profile = user_api.get_user_profile()
        print("用户资料:", profile)
    
    # 测试登出
    result = user_api.logout_user()
    print("登出结果:", result)